package ph.loong.deliveryman.http;

import android.content.SharedPreferences;

import java.io.IOException;
import java.util.HashSet;

import okhttp3.Interceptor;
import okhttp3.Response;
import ph.loong.deliveryman.app.MyApplication;

/**
 * Author jc.lu.
 * Dates 2018/2/22.
 * Email Tbsupland@163.com.
 * desc
 */

public class ReceivedCookiesInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            HashSet<String> cookies = new HashSet<>();
            for (String header : originalResponse.headers("Set-Cookie")) {
                //响应头为 PHPSESSID=9r4vbmvditj1rq4c7gunnu2c42; path=/
                //去除path=/
                header = header.substring(0, header.indexOf(";") + 1);
                cookies.add(header);
            }
            SharedPreferences.Editor config = MyApplication.Companion.getContext().getSharedPreferences("config",
                    MyApplication.Companion.getContext().MODE_PRIVATE)
                    .edit();
            config.putStringSet("cookie", cookies);
            config.commit();
        }

        return originalResponse;
    }
}
